const nodemailer = require('nodemailer')
const crypto = require('crypto')
const { logger } = require('./logger')

/**
 * 邮件服务工具类
 * 处理各种邮件发送需求
 */
class EmailService {
  constructor() {
    this.transporter = null
    this.initializeTransporter()
  }

  /**
   * 初始化邮件传输器
   */
  initializeTransporter() {
    try {
      this.transporter = nodemailer.createTransport({
        host: process.env.SMTP_HOST,
        port: parseInt(process.env.SMTP_PORT) || 587,
        secure: process.env.SMTP_SECURE === 'true', // true for 465, false for other ports
        auth: {
          user: process.env.SMTP_USER,
          pass: process.env.SMTP_PASS
        },
        tls: {
          rejectUnauthorized: false
        }
      })

      // 验证连接配置
      this.transporter.verify((error, success) => {
        if (error) {
          logger.error('邮件服务配置错误:', error)
        } else {
          logger.info('邮件服务已就绪')
        }
      })
    } catch (error) {
      logger.error('初始化邮件服务失败:', error)
    }
  }

  /**
   * 生成验证码
   * @param {number} length - 验证码长度
   * @returns {string} 验证码
   */
  generateVerificationCode(length = 6) {
    const digits = '0123456789';
    let code = '';
    for (let i = 0; i < length; i++) {
      code += digits[Math.floor(Math.random() * digits.length)];
    }
    return code;
  }

  /**
   * 生成重置令牌
   * @returns {string} 重置令牌
   */
  generateResetToken() {
    return crypto.randomBytes(32).toString('hex');
  }

  /**
   * 发送邮件的通用方法
   * @param {Object} mailOptions - 邮件选项
   * @returns {Promise<Object>} 发送结果
   */
  async sendMail(mailOptions) {
    try {
      if (!this.transporter) {
        throw new Error('邮件服务未初始化')
      }

      const defaultOptions = {
        from: `"${process.env.SMTP_FROM_NAME || 'CU MR BULL'}" <${process.env.SMTP_FROM_EMAIL || process.env.SMTP_USER}>`
      }

      const finalOptions = { ...defaultOptions, ...mailOptions }
      const result = await this.transporter.sendMail(finalOptions)

      logger.info('邮件发送成功:', { messageId: result.messageId })
      return {
        success: true,
        messageId: result.messageId
      }
    } catch (error) {
      logger.error('邮件发送失败:', error)
      return {
        success: false,
        error: error.message
      }
    }
  }

  /**
   * 发送欢迎邮件
   * @param {string} email - 收件人邮箱
   * @param {string} username - 用户名
   * @returns {Promise<Object>} 发送结果
   */
  async sendWelcomeEmail(email, username) {
    const subject = '欢迎加入 CU MR BULL！';
    const html = `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8">
        <style>
          .container { max-width: 600px; margin: 0 auto; font-family: Arial, sans-serif; }
          .header { background-color: #d32f2f; color: white; padding: 20px; text-align: center; }
          .content { padding: 30px; background-color: #f9f9f9; }
          .footer { padding: 20px; text-align: center; color: #666; font-size: 12px; }
          .button { display: inline-block; padding: 12px 24px; background-color: #d32f2f; color: white; text-decoration: none; border-radius: 5px; margin: 20px 0; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h1>🐂 CU MR BULL</h1>
            <p>正宗韩式料理</p>
          </div>
          <div class="content">
            <h2>欢迎，${username}！</h2>
            <p>感谢您注册 CU MR BULL 会员！我们很高兴您加入我们的大家庭。</p>
            <p>作为会员，您将享受到：</p>
            <ul>
              <li>🎯 专属会员优惠</li>
              <li>🎁 积分奖励系统</li>
              <li>📱 便捷在线订餐</li>
              <li>🚚 优先配送服务</li>
              <li>🎉 生日特别优惠</li>
            </ul>
            <p>现在就开始探索我们的美味韩式料理吧！</p>
            <a href="${process.env.FRONTEND_URL || 'https://app.cumrbull.com'}" class="button">立即开始订餐</a>
          </div>
          <div class="footer">
            <p>CU MR BULL - 宇宙守护者的韩式能量</p>
            <p>如有疑问，请联系客服：${process.env.SUPPORT_EMAIL || 'support@cumrbull.com'}</p>
          </div>
        </div>
      </body>
      </html>
    `;

    return await this.sendMail({
      to: email,
      subject,
      html
    });
  }

  /**
   * 发送邮箱验证码
   * @param {string} email - 收件人邮箱
   * @param {string} verificationCode - 验证码
   * @returns {Promise<Object>} 发送结果
   */
  async sendEmailVerification(email, verificationCode) {
    const subject = 'CU MR BULL - 邮箱验证码';
    const html = `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8">
        <style>
          .container { max-width: 600px; margin: 0 auto; font-family: Arial, sans-serif; }
          .header { background-color: #d32f2f; color: white; padding: 20px; text-align: center; }
          .content { padding: 30px; background-color: #f9f9f9; text-align: center; }
          .code { font-size: 32px; font-weight: bold; color: #d32f2f; letter-spacing: 5px; margin: 20px 0; padding: 15px; background-color: white; border: 2px dashed #d32f2f; }
          .footer { padding: 20px; text-align: center; color: #666; font-size: 12px; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h1>🐂 CU MR BULL</h1>
            <p>邮箱验证</p>
          </div>
          <div class="content">
            <h2>验证您的邮箱地址</h2>
            <p>请使用以下验证码完成邮箱验证：</p>
            <div class="code">${verificationCode}</div>
            <p>验证码有效期为 <strong>10分钟</strong>，请尽快使用。</p>
            <p>如果您没有请求此验证码，请忽略此邮件。</p>
          </div>
          <div class="footer">
            <p>CU MR BULL - 宇宙守护者的韩式能量</p>
            <p>此邮件由系统自动发送，请勿回复</p>
          </div>
        </div>
      </body>
      </html>
    `;

    return await this.sendMail({
      to: email,
      subject,
      html
    });
  }

  /**
   * 发送密码重置邮件
   * @param {string} email - 收件人邮箱
   * @param {string} resetToken - 重置令牌
   * @param {string} username - 用户名
   * @returns {Promise<Object>} 发送结果
   */
  async sendPasswordResetEmail(email, resetToken, username) {
    const resetUrl = `${process.env.FRONTEND_URL || 'https://app.cumrbull.com'}/reset-password?token=${resetToken}`;
    const subject = 'CU MR BULL - 密码重置请求';
    const html = `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8">
        <style>
          .container { max-width: 600px; margin: 0 auto; font-family: Arial, sans-serif; }
          .header { background-color: #d32f2f; color: white; padding: 20px; text-align: center; }
          .content { padding: 30px; background-color: #f9f9f9; }
          .footer { padding: 20px; text-align: center; color: #666; font-size: 12px; }
          .button { display: inline-block; padding: 12px 24px; background-color: #d32f2f; color: white; text-decoration: none; border-radius: 5px; margin: 20px 0; }
          .warning { background-color: #fff3cd; border: 1px solid #ffeaa7; padding: 15px; border-radius: 5px; margin: 20px 0; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h1>🐂 CU MR BULL</h1>
            <p>密码重置</p>
          </div>
          <div class="content">
            <h2>密码重置请求</h2>
            <p>亲爱的 ${username}，</p>
            <p>我们收到了您的密码重置请求。请点击下面的按钮来重置您的密码：</p>
            <div style="text-align: center;">
              <a href="${resetUrl}" class="button">重置密码</a>
            </div>
            <p>或者复制以下链接到浏览器地址栏：</p>
            <p style="word-break: break-all; background-color: #f0f0f0; padding: 10px; border-radius: 3px;">${resetUrl}</p>
            <div class="warning">
              <strong>⚠️ 安全提醒：</strong>
              <ul>
                <li>此链接有效期为 <strong>1小时</strong></li>
                <li>如果您没有请求密码重置，请忽略此邮件</li>
                <li>为了您的账户安全，请不要将此链接分享给他人</li>
              </ul>
            </div>
          </div>
          <div class="footer">
            <p>CU MR BULL - 宇宙守护者的韩式能量</p>
            <p>如有疑问，请联系客服：${process.env.SUPPORT_EMAIL || 'support@cumrbull.com'}</p>
          </div>
        </div>
      </body>
      </html>
    `;

    return await this.sendMail({
      to: email,
      subject,
      html
    });
  }

  /**
   * 发送订单确认邮件
   * @param {string} email - 收件人邮箱
   * @param {Object} orderData - 订单数据
   * @returns {Promise<Object>} 发送结果
   */
  async sendOrderConfirmationEmail(email, orderData) {
    const { orderNumber, items, totalAmount, deliveryAddress, estimatedTime } = orderData;
    const subject = `CU MR BULL - 订单确认 #${orderNumber}`;
    
    const itemsHtml = items.map(item => `
      <tr>
        <td style="padding: 10px; border-bottom: 1px solid #eee;">${item.name}</td>
        <td style="padding: 10px; border-bottom: 1px solid #eee; text-align: center;">${item.quantity}</td>
        <td style="padding: 10px; border-bottom: 1px solid #eee; text-align: right;">¥${item.price.toFixed(2)}</td>
      </tr>
    `).join('');

    const html = `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8">
        <style>
          .container { max-width: 600px; margin: 0 auto; font-family: Arial, sans-serif; }
          .header { background-color: #d32f2f; color: white; padding: 20px; text-align: center; }
          .content { padding: 30px; background-color: #f9f9f9; }
          .footer { padding: 20px; text-align: center; color: #666; font-size: 12px; }
          .order-table { width: 100%; border-collapse: collapse; margin: 20px 0; background-color: white; }
          .order-table th { background-color: #f5f5f5; padding: 12px; text-align: left; border-bottom: 2px solid #ddd; }
          .total-row { font-weight: bold; background-color: #f9f9f9; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h1>🐂 CU MR BULL</h1>
            <p>订单确认</p>
          </div>
          <div class="content">
            <h2>感谢您的订单！</h2>
            <p><strong>订单号：</strong>${orderNumber}</p>
            <p><strong>预计送达时间：</strong>${estimatedTime}</p>
            
            <h3>订单详情</h3>
            <table class="order-table">
              <thead>
                <tr>
                  <th>商品名称</th>
                  <th style="text-align: center;">数量</th>
                  <th style="text-align: right;">价格</th>
                </tr>
              </thead>
              <tbody>
                ${itemsHtml}
                <tr class="total-row">
                  <td colspan="2" style="padding: 15px; text-align: right;">总计：</td>
                  <td style="padding: 15px; text-align: right;">¥${totalAmount.toFixed(2)}</td>
                </tr>
              </tbody>
            </table>
            
            ${deliveryAddress ? `
              <h3>配送地址</h3>
              <p style="background-color: white; padding: 15px; border-radius: 5px;">${deliveryAddress}</p>
            ` : ''}
            
            <p>我们正在精心准备您的美食，请耐心等待。您可以随时在APP中查看订单状态。</p>
          </div>
          <div class="footer">
            <p>CU MR BULL - 宇宙守护者的韩式能量</p>
            <p>如有疑问，请联系客服：${process.env.SUPPORT_EMAIL || 'support@cumrbull.com'}</p>
          </div>
        </div>
      </body>
      </html>
    `;

    return await this.sendMail({
      to: email,
      subject,
      html
    });
  }

  /**
   * 发送促销邮件
   * @param {string} email - 收件人邮箱
   * @param {Object} promotionData - 促销数据
   * @returns {Promise<Object>} 发送结果
   */
  async sendPromotionEmail(email, promotionData) {
    const { title, description, discountCode, validUntil, imageUrl } = promotionData;
    const subject = `CU MR BULL - ${title}`;
    
    const html = `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8">
        <style>
          .container { max-width: 600px; margin: 0 auto; font-family: Arial, sans-serif; }
          .header { background-color: #d32f2f; color: white; padding: 20px; text-align: center; }
          .content { padding: 30px; background-color: #f9f9f9; text-align: center; }
          .footer { padding: 20px; text-align: center; color: #666; font-size: 12px; }
          .button { display: inline-block; padding: 12px 24px; background-color: #d32f2f; color: white; text-decoration: none; border-radius: 5px; margin: 20px 0; }
          .promo-code { font-size: 24px; font-weight: bold; color: #d32f2f; background-color: white; padding: 15px; border: 2px dashed #d32f2f; margin: 20px 0; }
          .promo-image { max-width: 100%; height: auto; border-radius: 10px; margin: 20px 0; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h1>🐂 CU MR BULL</h1>
            <p>特别优惠</p>
          </div>
          <div class="content">
            <h2>${title}</h2>
            ${imageUrl ? `<img src="${imageUrl}" alt="促销图片" class="promo-image">` : ''}
            <p>${description}</p>
            ${discountCode ? `
              <p>使用优惠码：</p>
              <div class="promo-code">${discountCode}</div>
            ` : ''}
            <p><strong>优惠有效期至：${validUntil}</strong></p>
            <a href="${process.env.FRONTEND_URL || 'https://app.cumrbull.com'}" class="button">立即订餐</a>
          </div>
          <div class="footer">
            <p>CU MR BULL - 宇宙守护者的韩式能量</p>
            <p>如不想接收此类邮件，请联系客服取消订阅</p>
          </div>
        </div>
      </body>
      </html>
    `;

    return await this.sendMail({
      to: email,
      subject,
      html
    });
  }
}

const emailService = new EmailService()

module.exports = emailService